// 本地数据存储服务

export interface PatientData {
  questionnaire: QuestionnaireResult | null
  questionnaireHistory: QuestionnaireResult[]
  boneDensity: BoneDensityResult | null
  boneDensityHistory: BoneDensityResult[]
  exercise: ExerciseRecord[]
  medication: MedicationRecord[]
  lastUpdated: string
}

export interface QuestionnaireResult {
  date: string
  score: number
  riskLevel: string
  answers: number[]
}

export interface BoneDensityResult {
  date: string
  type: string
  tScore: number
  zScore: number
  diagnosis: string
}

export interface ExerciseRecord {
  date: string
  duration: number
  exercises: string[]
  calories: number
}

export interface MedicationRecord {
  id: string
  name: string
  time: string
  frequency: string
  completed: boolean
  completedDate: string[]
}

export class LocalStorageService {
  private readonly KEY = 'patient_health_data'

  // 初始化患者数据
  initializeData(): PatientData {
    return {
      questionnaire: null,
      questionnaireHistory: [],
      boneDensity: null,
      boneDensityHistory: [],
      exercise: [],
      medication: [],
      lastUpdated: new Date().toISOString()
    }
  }

  // 获取所有数据
  getAllData(): PatientData {
    try {
      const data = AppStorage.Get<string>(this.KEY)
      if (data) {
        return JSON.parse(data) as PatientData
      }
    } catch (e) {
      console.error('读取数据失败:', e)
    }
    return this.initializeData()
  }

  // 保存所有数据
  saveAllData(data: PatientData): void {
    try {
      data.lastUpdated = new Date().toISOString()
      AppStorage.SetOrCreate(this.KEY, JSON.stringify(data))
    } catch (e) {
      console.error('保存数据失败:', e)
    }
  }

  // 保存问卷结果
  saveQuestionnaireResult(result: QuestionnaireResult): void {
    const data = this.getAllData()
    data.questionnaire = result
    // 添加到历史记录
    data.questionnaireHistory.push(result)
    this.saveAllData(data)
  }

  // 获取问卷结果
  getQuestionnaireResult(): QuestionnaireResult | null {
    return this.getAllData().questionnaire
  }

  // 获取问卷历史记录
  getQuestionnaireHistory(): QuestionnaireResult[] {
    return this.getAllData().questionnaireHistory
  }

  // 保存骨密度检测结果
  saveBoneDensityResult(result: BoneDensityResult): void {
    const data = this.getAllData()
    data.boneDensity = result
    // 添加到历史记录
    data.boneDensityHistory.push(result)
    this.saveAllData(data)
  }

  // 获取骨密度检测结果
  getBoneDensityResult(): BoneDensityResult | null {
    return this.getAllData().boneDensity
  }

  // 获取骨密度检测历史记录
  getBoneDensityHistory(): BoneDensityResult[] {
    return this.getAllData().boneDensityHistory
  }

  // 添加运动记录
  addExerciseRecord(record: ExerciseRecord): void {
    const data = this.getAllData()
    data.exercise.push(record)
    this.saveAllData(data)
  }

  // 获取所有运动记录
  getAllExerciseRecords(): ExerciseRecord[] {
    return this.getAllData().exercise
  }

  // 获取本周运动统计
  getWeeklyExerciseStats(): { totalMinutes: number; sessions: number; calories: number } {
    const records = this.getAllExerciseRecords()
    const today = new Date()
    const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)

    const weekRecords = records.filter(r => {
      const recordDate = new Date(r.date)
      return recordDate >= weekAgo && recordDate <= today
    })

    let totalMinutes = 0
    let calories = 0
    for (let i = 0; i < weekRecords.length; i++) {
      totalMinutes += weekRecords[i].duration
      calories += weekRecords[i].calories
    }

    return {
      totalMinutes: totalMinutes,
      sessions: weekRecords.length,
      calories: calories
    }
  }

  // 获取本月运动统计
  getMonthlyExerciseStats(): { totalMinutes: number; sessions: number; calories: number } {
    const records = this.getAllExerciseRecords()
    const today = new Date()
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)

    const monthRecords = records.filter(r => {
      const recordDate = new Date(r.date)
      return recordDate >= monthStart && recordDate <= today
    })

    let totalMinutes = 0
    let calories = 0
    for (let i = 0; i < monthRecords.length; i++) {
      totalMinutes += monthRecords[i].duration
      calories += monthRecords[i].calories
    }

    return {
      totalMinutes: totalMinutes,
      sessions: monthRecords.length,
      calories: calories
    }
  }

  // 添加用药提醒
  addMedicationReminder(record: MedicationRecord): void {
    const data = this.getAllData()
    data.medication.push(record)
    this.saveAllData(data)
  }

  // 获取所有用药提醒
  getAllMedicationReminders(): MedicationRecord[] {
    return this.getAllData().medication
  }

  // 标记用药完成
  markMedicationCompleted(medicationId: string): void {
    const data = this.getAllData()
    const medication = data.medication.find(m => m.id === medicationId)
    if (medication) {
      medication.completed = true
      medication.completedDate.push(new Date().toISOString().split('T')[0])
    }
    this.saveAllData(data)
  }

  // 清空所有数据
  clearAllData(): void {
    AppStorage.SetOrCreate(this.KEY, JSON.stringify(this.initializeData()))
  }
}

export const storageService = new LocalStorageService()
